﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace EntityFramework.OT.Demo.UnitTest
{
    using EntityFramework.OT.Demo.Data;

    [TestClass]
    public class UpdateTests
    {
        [TestMethod]
        public void TestUpdateProperties()
        {
            // Get first employee.
            var employee = GetTests.GetFirstEmployee();

            // Create a random name.
            int randomLength = TestHelper.RandomInt(1, 10);
            string randomName = TestHelper.RandomString(randomLength);

            // Set name and update.
            employee.FirstName = randomName;
            var result = UpdateEntity(employee.OperationTracker);

            // Update changes
            result.ApplyChanges(employee);
            // Check that name has been updated.
            Assert.IsTrue(employee.FirstName == randomName);
        }

        [TestMethod]
        public void TestAddCustomerOrder()
        {
            // Get customer
            var customer = GetTests.GetFirstCustomer();

            // Get orders for customer.
            var orders = GetTests.GetCustomerOrders(customer.CustomerID);
            int orderCount = orders.Count;

            // Create new order.
            var newOrder = new Order();
            // Add order to customer.
            customer.Orders.Add(newOrder);

            // Update
            UpdateEntity(customer.OperationTracker);
            // Get orders
            orders = GetTests.GetCustomerOrders(customer.CustomerID).ToList();
            Assert.IsTrue(orders.Count == orderCount + 1, "Order did not get added.");
        }

        /// <summary>
        /// A function that accepts an <see cref="ObjectOperationTracker"/> and
        /// updates the operations using the <see cref="NorthWindEntities"/> context.
        /// </summary>
        /// <param name="operation">The operation to update.</param>
        /// <returns>The operation result of the update.</returns>
        public static ObjectOperationTracker UpdateEntity(ObjectOperationTracker operation)
        {
            Assert.IsNotNull(operation);
            using (var context = new NorthWindEntities())
            {
                var entity = context.ApplyChanges(operation);
                Assert.IsNotNull(entity);
                context.SaveChanges();
                return entity.OperationTracker;
            }
        }
    }
}
